import Flutter
import UIKit
import asl

public class SwiftLogcatViewerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler {
    var eventSink : FlutterEventSink?
    var thread : Thread?
    var isStop = false
    public static func register(with registrar: FlutterPluginRegistrar) {
      let channel = FlutterMethodChannel(name: "LogcatViewerPlugin/controrller", binaryMessenger: registrar.messenger())
      let instance = SwiftLogcatViewerPlugin()
      registrar.addMethodCallDelegate(instance, channel: channel)

      let evenChannel = FlutterEventChannel(name:"LogcatViewerPlugin/listen", binaryMessenger: registrar.messenger())
      evenChannel.setStreamHandler(instance)
    }

    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
  //         result("iOS " + UIDevice.current.systemVersion)
        if call.method=="startLogInfo" {
            /// 闭包内直接执行代码
            Thread.detachNewThreadSelector(#selector(runLogcatSubscriber), toTarget: self, with: nil)
        } else if call.method=="stopLogInfo" {
            isStop = true;
        }
    }

    @objc private func runLogcatSubscriber() {
        var query : asl_object_t = asl_new(UInt32(ASL_TYPE_QUERY))
//            NSString *pidString = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]];
        
        var pidString : NSString = NSString.init(format: "%d", ProcessInfo.processInfo)
        let resultInt = asl_set_query(query, ASL_KEY_PID, pidString.utf8String, UInt32(ASL_QUERY_OP_EQUAL))
        print("response resultInt = "+String(resultInt))
        
        var response : aslresponse? = asl_search(query, query)
        print("response 1111")
        var aslMessage : aslmsg? = nil
        while !isStop {
//            print("response 222")
            aslMessage = asl_next(response)
//            print("response 333")
            if (aslMessage == nil) {
//                print("response 444")
               continue
            }
//            print("response 555")
            let logStr = asl_get(aslMessage, ASL_KEY_MSG)
            print(logStr)
            if (logStr != nil) {
                sendEventToStream(data: String.init(cString:logStr!))
            }
//            SystemLogMessage.logMessageFromASLMessage(aslMessage)
//                [logMessages addObject:[SystemLogMessage logMessageFromASLMessage:aslMessage]];
            }
        
        asl_release(response);
    }
    
    private func logMessageFromASLMessage(aslMessage : aslmsg) {
        
    }
    
    
    private func sendEventToStream(data: String) {
        // 判断当前线程是否是主线程
            if Thread.current.isMainThread {
                // UI 事件
                self.eventSink?(data)
            } else {
                // 切换到 main 线程，处理
                DispatchQueue.main.async {
                    self.sendEventToStream(data: data)
                    // 结束事件，防止造成递归循环
                    return
                }
            }
    }
    
    
    public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        self.eventSink = events
        return nil;
    }

    public func onCancel(withArguments arguments: Any?) -> FlutterError? {
        self.eventSink = nil
        return nil;
    }
}
